package com.example.administrator.yanfoxconn.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.ActListAdapter;
import com.example.administrator.yanfoxconn.bean.ActivityMsg;
import com.example.administrator.yanfoxconn.bean.LWInfo;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.HttpConnectionUtil;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.SwipterMenuTest;
import com.example.administrator.yanfoxconn.widget.TwoPopupWindow;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 總務 隱患通報 專案列表
 * Created by Song on 2022/4/2.
 */
public class LWCaseListActivity extends BaseActivity implements View.OnClickListener {

    private final int MESSAGE_SET_CASE=11;


    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.tv_title)
    TextView tvTitle;//標題
    @BindView(R.id.btn_title_right)
    Button btnNew;//新增
    @BindView(R.id.ib_title_right)
    ImageButton ibmenu;//新增

    @BindView(R.id.tv_tip)
    TextView tvTip;//提示

    @BindView(R.id.lv_people)
    SwipterMenuTest lvPeople;

    private List<LWInfo> lwInfos;
    private ActListAdapter actAdapter;
    private SwipeMenuCreator creator;
    private int width,height;
    private TwoPopupWindow twoPopupWindow;
    private LWCaseListActivity mContext = this;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_act_list);
        ButterKnife.bind(this);
        WindowManager wm = this.getWindowManager();

        width = wm.getDefaultDisplay().getWidth();
        height = wm.getDefaultDisplay().getHeight();
        btnBack.setOnClickListener(this);
        ibmenu.setBackgroundResource(R.drawable.ic_baseline_add_circle_outline_24);
        ibmenu.setVisibility(View.VISIBLE);
        ibmenu.setOnClickListener(this);
        tvTitle.setText("專案列表");
        lvPeople.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(mContext,ActEndActivity.class);
                intent.putExtra("item",actList.get(i));
                startActivity(intent);
            }
        });
        ItemOnLongClick1();

    }


    private void ItemOnLongClick1() {
//注：setOnCreateContextMenuListener是与下面onContextItemSelected配套使用的
        lvPeople.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
                    @Override
                    public void onCreateContextMenu(ContextMenu menu, View v,
                                                    ContextMenu.ContextMenuInfo menuInfo) {

                        //1.通过手动添加来配置上下文菜单选项
                        menu.add(0, 0, 0, "啟用");
                        menu.add(0, 1, 0, "禁用");
                        menu.add(0, 2, 0, "删除");

                        //2.通过xml文件来配置上下文菜单选项
//                        MenuInflater mInflater = getMenuInflater();
//                        mInflater.inflate(R.menu.menu_cpc, menu);
                        //super.onCreateContextMenu(menu, v, menuInfo);
                    }
                });
    }

    // 长按菜单响应函数
    public boolean onContextItemSelected(MenuItem item) {

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
                .getMenuInfo();
        //MID = (int) info.id;// 这里的info.id对应的就是数据库中_id的值
        int posi = info.position;
        switch (item.getItemId()) {
            case 0:
                // 結束
                Toast.makeText(mContext,
                        actList.get(posi).getAct_id(),
                        Toast.LENGTH_SHORT).show();
                break;
            case 1:
                // 修改操作
                Toast.makeText(mContext,
                        actList.get(posi).getAct_award(),
                        Toast.LENGTH_SHORT).show();
                break;
            case 2:
                // 删除操作
                    delMessage(actList.get(posi).getAct_id());
                break;

            default:
                break;
        }
        return super.onContextItemSelected(item);

    }

private void ItemOnLongClick2() {
    lvPeople.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                       final int position, long id) {
            //list.remove(arg2);
            new AlertDialog.Builder(mContext)
                    .setTitle("对Item进行操作")
                    .setItems(R.array.thread_menu,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    String[] PK = getResources()
                                            .getStringArray(
                                                    R.array.thread_menu);
                                    Toast.makeText(
                                            mContext,
                                            PK[which], Toast.LENGTH_LONG)
                                            .show();
                                    if (PK[which].equals("删除")) {
                                        // 按照这种方式做删除操作，这个if内的代码有bug，实际代码中按需操作
//
                                    }
                                }
                            })
                    .setNegativeButton("取消",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    // TODO Auto-generated method stub
                                }
                            }).show();
            return true;
        }
    });
}

    public int dp2px(float dipValue) {
        final float scale = this.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_title_left:
                finish();
                break;
            case R.id.btn_search:
                break;
            case R.id.ib_title_right:

                break;
        }
    }
    class OnClickLintener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.ll_code:
                    Intent intent = new Intent(mContext, ActReleaseActivity.class);
                    startActivity(intent);
                    break;
                case R.id.ll_write:
                    Intent intent3 = new Intent(mContext, ActHistoryListActivity.class);
                    startActivity(intent3);
                    break;
            }
        }
    }
    //查詢活動
    private void getMessage() {
        if (FoxContext.getInstance().getLoginId().equals("")) {
            ToastUtils.showShort(this, "登錄超時,請重新登陸");
            return;
        }
        final String url = Constants.HTTP_LW_CASE_LIST ; //此處寫上自己的URL
            showDialog();
            new Thread() {
                @Override
                public void run() {
                    //把网络访问的代码放在这里
                   String result = HttpUtils.queryStringForGet(url);

                    Log.e("---------", "==fff===" + url);
                    Gson gson = new Gson();
                    String response = result;
                    dismissDialog();
                    if (result != null) {
                        Log.e("---------", "result==fff===" + response);
                        JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                        String errCode = jsonObject.get("code").getAsString();
                        if (errCode.equals("200")) {

                            JsonArray arrayDep = jsonObject.get("data").getAsJsonArray();
                            lwInfos = new ArrayList<LWInfo>();
                            for (JsonElement type1 : arrayDep) {
                                LWInfo humi = gson.fromJson(type1, LWInfo.class);
                                lwInfos.add(humi);
                            }


                            Message message = new Message();
                            message.what = MESSAGE_SET_CASE;
                            mHandler.sendMessage(message);

                        }
                    }
                }
            }.start();
    }

    //刪除活動
    private void delMessage(String act_id) {
        if (FoxContext.getInstance().getLoginId().equals("")) {
            ToastUtils.showShort(this, "登錄超時,請重新登陸");
            return;
        }
        final String url = Constants.HTTP_ACTIVITY_JSON_SERVLET; //此處寫上自己的URL

        JsonObject object = new JsonObject();
        object.addProperty("flag","actDelete");
        object.addProperty("act_id",act_id);

        Log.e("-----object------",  object.toString());

        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里
                try {
                    showDialog();
                    Log.e("---------", "==fff===" + url);
                    String result = HttpConnectionUtil.doPostJsonObject(url, object);
                    dismissDialog();
                    Gson gson = new Gson();
                    if (result != null) {
                        Log.e("---------", "result==fff===" + result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("errCode").getAsString();
                        if (errCode.equals("200")) {
                            Message message = new Message();
                            message.what = Constants.MESSAGE_TOAST;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);

                        } else{
                            Message message = new Message();
                            message.what = Constants.MESSAGE_TOAST;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);
                        }
                    }else{
                        Message message = new Message();
                        message.what = Constants.MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                        finish();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }.start();
    }
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case Constants.MESSAGE_TOAST://Toast彈出
                    worningAlert(msg.obj.toString(),Constants.MESSAGE_TOAST);
                    //ToastUtils.showLong(mContext, msg.obj.toString());
//                    finish();
                    break;
                case MESSAGE_SET_CASE://text賦值

                        actAdapter = new ActListAdapter(mContext, lwInfos);
                        lvPeople.setAdapter(actAdapter);
                    break;
                case Constants.MESSAGE_DELETE_SUCCESS://提交響應

                    break;
                case Constants.MESSAGE_NOT_NET:
                    ToastUtils.showLong(mContext, "網絡錯誤，請稍後重試！");
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        getMessage();
    }

    private void aboutAlert(String msg, final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("確認信息")
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (type==Constants.MESSAGE_TOAST){
                            finish();
                        }else if(type==Constants.MESSAGE_UP){
                            //check();
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (type==Constants.MESSAGE_TOAST){
                            finish();
                        }else if(type==Constants.MESSAGE_UP){
                            //check();
                        }
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }
    private void worningAlert(String msg, final int t) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息")
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (t==Constants.MESSAGE_TOAST) {
                            getMessage();
                        }
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

}
